package com.bridge.applets.utils;

import com.bridge.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@Component
public class FileUploadUtil {

    public String uploadPattern = "uploads";
    private static final String uploadDir = "workspace";
    public String filePath = System.getProperty("user.dir") + File.separator + uploadDir + File.separator;


    @Value("${file.upload.baseUrl}")
    public String baseUrl;

    public String uploadByName(MultipartFile file, String preDir, String fileName) {
        try {
            // 创建上传目录（如果不存在）
            Path uploadPath = Paths.get(filePath + preDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            // 保存文件到指定目录
            Path filePath = uploadPath.resolve(fileName);
            file.transferTo(filePath.toFile());
            log.info("uploadByName,transferTo:{},exist:{}", filePath.toFile().getAbsolutePath(),Files.exists(filePath));
            return baseUrl +uploadPattern + "/"+preDir+fileName;
        } catch (Exception io) {
            io.printStackTrace();
            throw new ServiceException("上传文件异常");
        }

    }
}
